#include "game.h"
#include "ui_game.h"
#include <QPainter>
#include <QDebug>
#include <QKeyEvent>
#include<QTime>
#include<QDebug>
#include<QMessageBox>

//每个格子的宽高度
#define grid_wh 40

game::game(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::game),
    timerId(-1),
    isPaused(false)
{
    ui->setupUi(this);
    setFixedSize(800, 800);
    score = new QLabel(this);
    score->setText("scores: "+ QString::number(scores));
    score->setFocusPolicy(Qt::NoFocus);
    score->setGeometry(0,0,100,20);
    score->setStyleSheet(QLabel_STYTLE);
    startButton = new QPushButton("start",this);
    startButton->setFocusPolicy(Qt::NoFocus);
    startButton->setGeometry(width()/2-30,height()/2+115,60,30);
    startButton->setStyleSheet(QPushButton_STYTLE);
    connect(startButton,&QPushButton::clicked,[&](){
           startButton->hide();
           score->setText("scores: 0");
           snakePos.setX(5);//设置蛇的起始位置为5行5列
           snakePos.setY(5);
           snakebody.append(QPoint(5, 5)); // 蛇头
           snakebody.append(QPoint(4, 5)); // 身体第一部分
           snakebody.append(QPoint(3, 5)); // 身体第二部分
           foodList.push_back(QPoint(5,7));
           foodList.push_back(QPoint(10,6));
           foodList.push_back(QPoint(13,15));
           foodList.push_back(QPoint(7,9));
           startTimer(500);
       });
    dir = 2;//朝左边
    connect(startButton, &QPushButton::clicked, this, &game::startGame);
    qsrand(QTime::currentTime().msec());

}

game::~game()
{
    delete ui;
}
void game::paintEvent(QPaintEvent *event)
{
    (void)event;

    QPainter painter(this);

    QPen pen(Qt::white);
    painter.setPen(pen);

    QBrush brush(Qt::red);
    painter.setBrush(brush);

    QBrush snakeBrush(Qt::black);
    painter.setBrush(snakeBrush);// 创建一个黑色笔刷，并确保它是实心的

//    rect().width()窗口矩形区域的宽度
    for(int i = 0 ; i < rect().width()/grid_wh ; i++ )
    {
        painter.drawLine(QPoint(i*grid_wh,0),QPoint(i*grid_wh,rect().height()));
    }

    //rect().height()/grid_wh总高度除每个格子的高度，得到一共有多少行
    for(int i = 0 ; i < rect().height()/grid_wh ; i++ )
    {
        painter.drawLine(QPoint(0,i*grid_wh),QPoint(rect().width(),i*grid_wh));
    }

    //画蛇
//    snakePos.x()*grid_wh把蛇的列数转为坐标
//    snakePos.y()*grid_wh把蛇的行数转为坐标

    for(int i = 0;i  <snakebody.size();++i)
        {
            if (i == 0)
            {
                painter.drawEllipse(snakebody[i].x()*grid_wh, snakebody[i].y()*grid_wh, grid_wh, grid_wh);
            } else
            {
                QBrush bodyBrush(Qt::red);
                painter.setBrush(bodyBrush);
                painter.drawEllipse(snakebody[i].x()*grid_wh, snakebody[i].y()*grid_wh, grid_wh, grid_wh);
            }
        }

        QBrush food(Qt::blue);
        painter.setBrush(food);
        for (int i = 0; i < foodList.size(); ++i)
        {
            painter.drawRect(foodList[i].x()*grid_wh,foodList[i].y()*grid_wh,grid_wh,grid_wh);
        }
//    qDebug() << "Snake body:" << snakebody;
//    qDebug() << "Snake brush color:" << snakeBrush.color();

}

void game::timerEvent(QTimerEvent *event)
{
    (void)event;
    if (isPaused)
        {
            return; // 如果游戏处于暂停状态，则不执行任何操作
        }
    QPoint nextPos = snakePos;
    switch (dir)
    {
    case 1://左边
        snakePos.setX(snakePos.x() - 1);
        break;
    case 2://右边
        snakePos.setX(snakePos.x() + 1);
        break;
    case 3://上面
        snakePos.setY(snakePos.y() - 1);
        break;
    case 4://下面
        snakePos.setY(snakePos.y() + 1);
        break;
    default:
        break;
    }

    // 检查蛇头是否撞到边界
       if (nextPos.x() < 0 || nextPos.x() >= rect().width() / grid_wh ||
           nextPos.y() < 0 || nextPos.y() >= rect().height() / grid_wh)
       {
           gameOver();
           return;
       }
       // 检查蛇头是否与身体相撞
               for (int i = 1; i < snakebody.size(); ++i)
               {
                   if (snakePos == snakebody[i])
                   {
                       gameOver();
                       return;
                   }
               }

    snakebody.removeLast(); // 移除最后一个元素，即蛇尾

    // 将蛇头的新位置添加到蛇体的开头
    snakebody.prepend(snakePos);

    // 检查蛇是否吃到食物
    for (int i = 0; i < foodList.size(); ++i)
    {
        if (foodList.at(i) == snakePos) // 注意这里我们除以 grid_wh 来匹配 foodList 中的存储方式
        {
            score->setText("scores: "+ QString::number(++scores));//增加得分
            // 蛇吃到了食物，增加蛇的长度
            snakebody.append(snakebody.last()); // 将蛇尾复制到蛇头位置

            // 从食物列表中移除该食物
            foodList.removeAt(i);
            generateFood(); // 生成新的食物
            break; // 跳出循环
        }
    }

    repaint();

}

void game::keyPressEvent(QKeyEvent *event)
{
    // 检查是否按下空格键
        if (event->key() == Qt::Key_Space)
        {
            // 切换暂停状态
            isPaused = !isPaused;
            if (isPaused)
            {
                killTimer(timerId); // 暂停游戏时停止计时器
            }
            else
            {
                timerId = startTimer(500); // 恢复游戏时重新启动计时器
            }
        }
        else
        {
            // ... 处理其他按键事件 ...
            if (!isPaused && event->key() == Qt::Key_Left)
            {
                dir = 1;
            }
            else if (!isPaused && event->key() == Qt::Key_Right)
            {
                dir = 2;
            }
            else if (!isPaused && event->key() == Qt::Key_Up)
            {
                dir = 3;
            }
            else if (!isPaused && event->key() == Qt::Key_Down)
            {
                dir = 4;
            }
        }
}
void game::generateFood()
{
    // 生成随机位置的食物，确保它不在蛇的身体上
    bool validFoodPosition = false;
       QPoint newFoodPos;
       do {
           int x = qrand() % (rect().width() / grid_wh) * grid_wh;
           int y = qrand() % ((rect().height() / grid_wh - 4) * 4) / 4 * grid_wh + 4 * grid_wh;
           newFoodPos = QPoint(x, y);
           validFoodPosition = true;
           for (const QPoint &bodyPart : snakebody)
           {
               if (bodyPart == newFoodPos)
               {
                   validFoodPosition = false;
                   break;
               }
           }
       } while (!validFoodPosition);

       foodList.append(newFoodPos / grid_wh);
       qDebug() << "Generated food at:" << newFoodPos;
}

void game::gameOver()
{
    QMessageBox msgBox;
    msgBox.setWindowTitle("Game Over");
    msgBox.setText("You lost! Score: " + QString::number(scores));
    msgBox.setStandardButtons(QMessageBox::Ok);
    msgBox.exec();
    disconnect(startButton, &QPushButton::clicked, this, &game::startGame);
    // 重置游戏
    startButton->show();
    scores = 0;
    snakebody.clear();
    snakePos.setX(5);
    snakePos.setY(5);
    dir = 1;
    foodList.clear();
    generateFood(); // 确保列表不为空
    startGame(); // 直接调用 startGame 函数
}
void game::startGame()
{
    // 隐藏开始按钮
    startButton->hide();

    // 重置得分
    scores = 0;
    score->setText("scores: " + QString::number(scores));

    // 重置蛇的位置和身体
    snakePos.setX(5); // 设置蛇的起始位置为5行5列
    snakePos.setY(5);
    snakebody.clear(); // 清空蛇身体
    snakebody.append(QPoint(5, 5)); // 蛇头
    snakebody.append(QPoint(4, 5)); // 身体第一部分
    snakebody.append(QPoint(3, 5)); // 身体第二部分

    // 重置方向
    dir = 2; // 朝左边

    // 重置食物列表
    foodList.clear();
    generateFood(); // 生成新的食物

}
